package com.mondo.financialwallet.presentation.ui.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.common.ui.BaseActivity;
import com.mondo.financialwallet.R;
import com.mondo.financialwallet.data.DataRepository;
import com.mondo.financialwallet.presentation.event.AlterNicknameEvent;
import com.mondo.financialwallet.presentation.event.LogOutEvent;
import com.mondo.financialwallet.presentation.event.ModifyAvatarEvent;
import com.mondo.financialwallet.presentation.utils.ActivityTitleBarHelper;
import com.mondo.financialwallet.presentation.utils.AndroidUtils;
import com.mondo.financialwallet.presentation.utils.Glide4Engine;
import com.mondo.financialwallet.presentation.utils.LocalConfigStorage;
import com.mondo.financialwallet.presentation.utils.Toasts;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.List;

import butterknife.Bind;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * 个人设置
 */
public class PersonalSettingsActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks{

    private static final String EXTRA_NICKNAME = "NICKNAME", EXTRA_UID = "UID",
            EXTRA_AVATAR = "AVATAR";

    private static final int REQ_CHOOSE = 2;

    public static void launch(Context context, String nickname, String uid, String avatar) {
        context.startActivity(
                new Intent(context, PersonalSettingsActivity.class)
                        .putExtra(EXTRA_NICKNAME, nickname)
                        .putExtra(EXTRA_UID, uid)
                        .putExtra(EXTRA_AVATAR, avatar)
        );
    }

    @Bind(R.id.sign_out_view) View mSignOutView;
    @Bind(R.id.alter_nickname_layout) View mAlterNicknameLayout;
    @Bind(R.id.security_settings_layout) View mSecuritySettingsLayout;
    @Bind(R.id.modify_avatar_layout) View mModityAvatarLayout;
//    @Bind(R.id.general_settings_layout) View mGeneralSettingsLayout;
    @Bind(R.id.user_id_text_view) TextView mUserIdTextView;
    @Bind(R.id.avatar_image) ImageView mAvatarImage;
    @Bind(R.id.nickname_text_view) TextView mNicknameTextView;

    private ProgressDialog mProgressDialog;

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Override
    protected void setStatusBar() {
        ActivityTitleBarHelper.setWhiteDarkColorStatus(this);
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_personal_settings;
    }

    @Override
    protected void initActions() {
        ActivityTitleBarHelper.init(this, R.string.title_personal_settings);

        // 昵称
        mNicknameTextView.setText(getIntent().getStringExtra(EXTRA_NICKNAME));

        // 用户ID
        mUserIdTextView.setText("UID: " + getIntent().getStringExtra(EXTRA_UID));

        // 修改昵称
        mAlterNicknameLayout.setOnClickListener(v ->
                AlterNicknameActivity.launch(this, getIntent().getStringExtra(EXTRA_NICKNAME)));

        // 安全设置
        mSecuritySettingsLayout.setOnClickListener(v -> SecuritySettingsActivity.launch(this));

        // 修改头像
        mModityAvatarLayout.setOnClickListener(v -> requestPermission());

        // 通用设置
        //mGeneralSettingsLayout.setOnClickListener(v -> GeneralSettingsActivity.launch(this));

        // 登出
        mSignOutView.setOnClickListener(v -> signOut());

        // 头像
        String avatar = getIntent().getStringExtra(EXTRA_AVATAR);
        if (!TextUtils.isEmpty(avatar)){
            Glide.with(mAvatarImage)
                    .load(avatar)
                    .dontAnimate()
                    .into(mAvatarImage);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            launchMatisse();
        } else if (requestCode == REQ_CHOOSE && resultCode == RESULT_OK) {
            Uri uri = Matisse.obtainResult(data).get(0);
            mAvatarImage.setImageURI(uri);

            // 上传头像
            submitNewPortrait(uri);
        }
    }

    private void submitNewPortrait(Uri uri) {
        if (mProgressDialog == null){
            mProgressDialog = ProgressDialog.show(this, null,
                    getString(R.string.message_uploading_avatar));
            DataRepository.get().modifyAvatar(AndroidUtils.uriToFile(this, uri), result -> {
                mProgressDialog.dismiss();
                mProgressDialog = null;

                if (result.isSuccess()){
                    Toasts.success(R.string.message_alter_success);
                    EventBus.getDefault().post(new ModifyAvatarEvent(uri));
                    finish();
                } else {
                    Toasts.failure(result.getMsg());
                }
            });
        }
    }

    private void requestPermission() {
        String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, permissions)) {
            String rationale = getString(R.string.please_approve_camera_permissions);
            EasyPermissions.requestPermissions(this, rationale, 0, permissions);
        } else {
            launchMatisse();
        }
    }

    private void launchMatisse(){
        Matisse.from(this)
                .choose(MimeType.allOf())
                .countable(true)
                .maxSelectable(1)
                .theme(R.style.Matisse_My)
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new Glide4Engine())
                .forResult(REQ_CHOOSE);
    }

    private void signOut() {
        LocalConfigStorage.get().singOut();
        startActivityAndFinish(new Intent(this, LoginActivity.class));
        EventBus.getDefault().post(new LogOutEvent());
    }

    @Subscribe
    public void alterNicknameEvent(AlterNicknameEvent event){
        mNicknameTextView.setText(event.getNickname());
    }

    @Subscribe
    public void logoutEvent(LogOutEvent event){
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        launchMatisse();
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(R.string.auto_authorization_failure)
                    .setRationale(R.string.please_manually_select_approve_camera_permissions).build().show();
        } else {
            Toasts.failure(R.string.authorization_failure);
        }
    }
}
